package com.dabai.dbutils.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import com.dabai.dbutils.data.ConstantValues;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


/**
 * 对于 app们的快捷操作
 *
 * @author BAI
 */
public class AppUtils {

    /**
     * 查询应用是否被冻结
     *
     * @param context     上下文
     * @param packageName 包名
     * @return boolean
     */
    public static boolean isFreeze(Context context, String packageName) {
        boolean state = false;
        try {
            state = context.getPackageManager().getPackageInfo(packageName, 0).applicationInfo.enabled;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return !state;
    }


    /**
     * 获得包名的应用程序名称
     *
     * @param context     上下文
     * @param packageName 包名
     * @return {@link String}
     */
    public static String getApplicationNameByPackageName(Context context, String packageName) {

        PackageManager pm = context.getPackageManager();
        String name;
        try {
            name = pm.getApplicationLabel(pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA)).toString();
        } catch (PackageManager.NameNotFoundException e) {
            name = "";
        }
        return name;
    }


    /**
     * 得到uid
     *
     * @param context 上下文
     * @return int
     */
    public static int getUid(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            @SuppressLint("WrongConstant") ApplicationInfo ai = pm.getApplicationInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            return ai.uid;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 是否系统应用程序
     *
     * @param context     上下文
     * @param packageName 包名
     * @return boolean
     */
    public static boolean isSystemApplication(Context context, String packageName) {
        PackageManager packageManager = context.getPackageManager();
        if (packageManager == null || packageName == null || packageName.length() == 0) {
            return false;
        }
        try {
            ApplicationInfo app = packageManager.getApplicationInfo(packageName, 0);
            return (app != null && (app.flags & ApplicationInfo.FLAG_SYSTEM) > 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 获取apk应用信息
     */
    @SuppressLint("QueryPermissionsNeeded")
    public static PackageInfo getApkPackageInfo(Context context, String apkPath) {
        if (!new File(apkPath).exists()) {
            return null;
        }
        return context.getPackageManager().getPackageArchiveInfo(apkPath, 0);
    }

    /**
     * 获取已安装的全部应用信息
     */
    @SuppressLint("QueryPermissionsNeeded")
    public static List<PackageInfo> getAllInstalledPackages(Context context) {
        return context.getPackageManager().getInstalledPackages(0);
    }

    /**
     * 获取用户安装包
     *
     * @param context 上下文
     * @return {@link List<PackageInfo>}
     */
    @SuppressLint("QueryPermissionsNeeded")
    public static List<PackageInfo> getUserInstalledPackages(Context context) {

        List<PackageInfo> result = new ArrayList<>();

        PackageManager pm = context.getPackageManager();

        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo packageInfo : packages) {
            // 判断系统/非系统应用
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) // 非系统应用
            {
                result.add(packageInfo);
            }
        }
        return result;
    }

    /**
     * 得到系统安装包
     *
     * @param context 上下文
     * @return {@link List<PackageInfo>}
     */
    @SuppressLint("QueryPermissionsNeeded")
    public static List<PackageInfo> getSystemInstalledPackages(Context context) {

        List<PackageInfo> result = new ArrayList<>();

        PackageManager pm = context.getPackageManager();

        List<PackageInfo> packages = pm.getInstalledPackages(0);
        for (PackageInfo packageInfo : packages) {
            // 判断系统/非系统应用
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) // 非系统应用
            {
                result.add(packageInfo);
            }
        }
        return result;
    }


    /**
     * 获得版本名称
     *
     * @param context 上下文
     * @return {@link String}
     */
    @Deprecated
    public static String getVersionName(Context context) {
        PackageInfo pInfo;
        try {
            pInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pInfo.versionName;
            //或者 pInfo.versionCode;

        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException("Could not get package version name: " + e);
        }
    }

    /**
     * 获取版本号
     */
    @Deprecated
    public static String getVersionCode(Context c) {
        try {
            PackageManager manager = c.getPackageManager();
            PackageInfo info = manager.getPackageInfo(c.getPackageName(), 0);
            return info.versionCode + "";
        } catch (Exception e) {
            e.printStackTrace();
            return ConstantValues.NULL;
        }
    }

    /**
     * 获取所有 支持某个 scheme 的app数量
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static int getSchemeSupportOpenSoftwareNumber(Context context, String scheme) {
        PackageManager packageManager = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(scheme));

        @SuppressLint("QueryPermissionsNeeded") List<ResolveInfo> activities = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_ALL);

        return activities.size();
    }


    /**
     * 获取所有支持某个 mime 的活动名
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static List<String> getMimeSupportOpenSoftwares(Context context, String mime) {
        PackageManager packageManager = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setType(mime);

        @SuppressLint("QueryPermissionsNeeded")
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_ALL);

        List<String> packageNames = new ArrayList<>();

        ApplicationInfo applicationInfo = null;

        for (ResolveInfo resolveInfo : activities) {
            try {
                applicationInfo = packageManager.getApplicationInfo(resolveInfo.activityInfo.packageName, 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            String title = (String) ((applicationInfo != null) ? packageManager.getApplicationLabel(applicationInfo) : "???");
            packageNames.add(title);
        }
        return packageNames;
    }


    /**
     * 获取所有安装的浏览器活动名
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static List<String> getBrowserList(Context context) {
        PackageManager packageManager = context.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("http://"));

        @SuppressLint("QueryPermissionsNeeded")
        List<ResolveInfo> activities = packageManager.queryIntentActivities(intent,
                PackageManager.MATCH_ALL);

        List<String> packageNames = new ArrayList<>();

        ApplicationInfo applicationInfo = null;

        for (ResolveInfo resolveInfo : activities) {
            try {
                applicationInfo = packageManager.getApplicationInfo(resolveInfo.activityInfo.packageName, 0);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            String title = (String) ((applicationInfo != null) ? packageManager.getApplicationLabel(applicationInfo) : "???");
            packageNames.add(title);
        }
        return packageNames;
    }


    /**
     * 某app是否安装
     *
     * @param context     当前上下文
     * @param packageName 目标包名
     * @return 布尔值
     */
    public static boolean isAppInstalled(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        Intent i = manager.getLaunchIntentForPackage(packageName);
        return i != null;
    }

    /**
     * 检查手机上是否安装了指定的软件
     * 需要权限
     *
     * @param context     上下文
     * @param packageName 包名
     * @return boolean
     */
    public static boolean isInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        @SuppressLint("QueryPermissionsNeeded")
        List<PackageInfo> packageInfo = packageManager.getInstalledPackages(0);
        if (packageInfo != null) {
            for (int i = 0; i < packageInfo.size(); i++) {
                String pkName = packageInfo.get(i).packageName;
                if (pkName.equals(packageName)) return true;
            }
        }
        return false;
    }


    /**
     * 检查是否安装app  此方法弃用
     */
    @Deprecated
    public boolean checkApkExist(Context context, String packageName) {
        if (TextUtils.isEmpty(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager()
                    .getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 打开应用程序
     * 通过包名打开app
     *
     * @param context     上下文
     * @param packageName 包名
     */
    public static void openApp(Context context, String packageName) {
        try {
            Intent resolveIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
            context.startActivity(resolveIntent);
        } catch (Exception e) {
            DabaiUtils.showToast(context,"无法打开指定应用!");
        }
    }

    /**
     * 安装apk
     *
     * @param context 上下文
     * @param file    文件
     */
    public static void installApk(Context context, File file) {

        if (null != file && file.exists()) {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                Uri contentUri = FileProvider.getUriForFile(
                        context
                        , context.getPackageName() + ".fileProvider"
                        , file);
                intent.setDataAndType(contentUri, "application/vnd.android.package-archive");

            } else {
                intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
            }

            context.startActivity(intent);

        } else {
            Toast.makeText(context, "文件不存在!", Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 卸载的apk
     * 调用系统卸载应用
     *
     * @param context     上下文
     * @param packageName 包名
     */
    public static void uninstallApk(Context context, String packageName) {
        Intent intent = new Intent(Intent.ACTION_DELETE);
        Uri packageURI = Uri.parse("package:" + packageName);
        intent.setData(packageURI);
        context.startActivity(intent);
    }

    /**
     * 打开已安装应用的详情
     */
    public static void openInstalledAppDetails(Context context, String packageName) {
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + packageName));
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    /**
     * 启用应用程序
     *
     * @param context     上下文
     * @param packageName 包名
     */
    public static void enableApp(Context context,String packageName){
        context.getPackageManager().setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0);
    }

    /**
     * 禁用应用程序
     *
     * @param context     上下文
     * @param packageName 包名
     */
    public static void disableApp(Context context,String packageName){
        context.getPackageManager().setApplicationEnabledSetting(packageName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 0);
    }

    /**
     * 静默安装apk
     *
     * @param context  上下文
     * @param filePath 文件路径
     * @return 0 means normal, 1 , 2 means other exception error
     */
    public static int silentInstallApk(Context context, String filePath) {

        File file = new File(filePath);

        if (filePath.length() == 0 || file.length() <= 0 || !file.exists() || !file.isFile()) {
            return 1;
        }

        String[] args = {"pm", "install", "-r", filePath};
        ProcessBuilder processBuilder = new ProcessBuilder(args);

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        int result;
        try {
            process = processBuilder.start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;

            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }

        if (successMsg.toString().contains("Success") || successMsg.toString().contains("success")) {
            result = 0;
        } else {
            result = 2;
        }
        return result;
    }

    /**
     * 沉默的卸载apk
     *
     * @param context     上下文
     * @param packageName 包名
     * @return 0 means normal, 1 , 2 means other exception error
     */
    public static int silentUninstallApk(Context context, String packageName) {

        String[] args = {"pm", "uninstall", packageName};
        ProcessBuilder processBuilder = new ProcessBuilder(args);

        Process process = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder errorMsg = new StringBuilder();
        int result;
        try {
            process = processBuilder.start();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;

            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }

        if (successMsg.toString().toLowerCase().contains("success")) {
            result = 0;
        } else {
            result = 2;
        }
        return result;
    }


}
